'use strict';
app.service('utilService',['$http','$cookies','$q','toaster',function($http, $cookies, $q, toaster){
    var loginUrl='/shop.bainaeco.com/sso/index.html#/access/login';

    this.get = function(opt){

        var defaults = {
            url:null,
            params:{}
        }

        defaults = angular.extend(defaults,opt);

        if($cookies.sessionId){
            defaults.params['sessionId'] = $cookies.sessionId;
        }

        var deferred = $q.defer();
        $http.get(defaults.url,{
            params:defaults.params
        }).then(function(response){
            switch (response.data.status){
                case 612:
                case 613:
                    location.href = loginUrl;
                    break;
            }
            deferred.resolve(response);
        },function(e){
            deferred.reject("连接服务器出错！");
        });
        return deferred.promise;
    }

    // call back
    this.api = function(opt){
        var defaults = {
            url:null,
            data:{},
            method:'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }

        angular.extend(defaults,opt);

        if(defaults.method == 'PUT'){
            defaults.data['_method'] = 'PUT';
        }else if(defaults.method == 'DELETE'){
            defaults.data['_method'] = 'DELETE';
        }

        if($cookies.sessionId){
            defaults.data['sessionId'] = $cookies.sessionId;
        }

        if(opt.url == null){
            alert('url is required.');
        }

        Object.toparams = function ObjecttoParams(obj) {
            var p = [];
            for (var key in obj) {
                p.push(key + '=' + encodeURIComponent(obj[key]));
            }
            return p.join('&');
        };

        var deferred = $q.defer();

        $http({
            url:defaults.url,
            withCredentials:true,
            method:'POST',
            data:Object.toparams(defaults.data),
            headers: defaults.headers
        }).then(function(response){
            switch (response.data.status){
                case 612:
                case 613:
                    location.href = loginUrl;
                    break;
            }
            deferred.resolve(response.data);
        },function(e){
            console.error(e);
            deferred.reject("连接服务器出错！");
        });
        return deferred.promise;
    }

    // pagination
    this.queryForPagingList = function($scope, opt){
        $scope.totalItems = 0;
        $scope.currentPage = 1;
        $scope.maxPageRow = 10;
        $scope.startRow = 0;
        $scope.endRow = 0;

        var defaults = {
            url:null,
            params:{
                start: ($scope.currentPage - 1) * $scope.maxPageRow,
                page: $scope.currentPage,
                length: $scope.maxPageRow
            }
        }
        if(opt.params){
            opt.params.start = defaults.params.start;
            opt.params.page = defaults.params.page;
            opt.params.length = defaults.params.length;

        }
        defaults = angular.extend(defaults,opt);

        $scope.pageChanged = function () {
            defaults.params.start = ($scope.currentPage - 1) * $scope.maxPageRow;
            defaults.params.page = $scope.currentPage;
            defaults.params.length = $scope.maxPageRow;
            callback();
        };

        if($cookies.sessionId){
            defaults.params['sessionId'] = $cookies.sessionId;
        }
        if(opt.url == null){
            alert('url is required.');
        }

        var callback = function(){

            $scope.app.loading=true;


            var deferred = $q.defer();
            $http.get(defaults.url,{
                params:defaults.params
            }).then(function(response){
                if(response.data.status){
                    switch (response.data.status){
                        case 612:
                        case 613:
                            //location.href = '#/access/login';

                            break;
                        default :
                            toaster.pop('error', "操作失败", "发生未知错误！请联系管理员");
                            break
                    }
                }else{
                    $scope.totalItems = response.data.totalCount;
                    $scope.list = response.data.list;
                    if(response.data.list.length > 0){
                        $scope.startRow = defaults.params.start + 1;
                        if(response.data.list.length == defaults.params.length){
                            $scope.endRow = defaults.params.length * defaults.params.page;
                        }else{
                            $scope.endRow = defaults.params.length * (defaults.params.page - 1) + response.data.list.length;
                        }
                    }
                }
                $scope.app.loading=false;
                deferred.resolve(response.data);
            },function(e){
                $scope.app.loading=false;
                console.error(e);
                toaster.pop('error', "读取数据失败", "连接服务器出错！");
                deferred.reject("连接服务器出错！");
            });
            return deferred.promise;
        }
        var deferred = $q.defer();
        callback().then(function(result){
            deferred.resolve(result);
        },function(e){
            console.error(e);
            deferred.reject("连接服务器出错！");
        });
        return deferred.promise;
    }

    this.modal = function($modal, $scope, opt){
        var defaults = {
            title:null,
            controller:null,
            message:null,
            data:{}
        }
        defaults = angular.extend(defaults,opt);

        if(opt.title == null){
            alert('Modal:title is required.');
            return false;
        } else if(opt.controller == null){
            alert('Modal:controller is required.');
            return false;
        } else if(opt.message == null){
            alert('Modal:message is required.');
            return false;
        }
        $scope.isDelModal = true;
        $modal.open({
            templateUrl:'tpl/blocks/modal_template.html',
            controller: defaults.controller,
            scope: $scope,
            size:'sm',
            resolve: {
                modalData: function () {
                    return {
                        title:defaults.title,
                        message:defaults.message,
                        data:defaults.data
                    };
                }
            }
        });
    }

}]);